package com.gjxx.netty.session;

import com.gjxx.common.tcp.PackageData;
import io.netty.channel.Channel;
import lombok.Data;

import java.net.SocketAddress;

@Data
public class Session {

    private String id;
    private String terminalPhone;
    private Channel channel = null;
    private boolean isAuthenticated = false;
    // 消息流水号 word(16) 按发送顺序从 0 开始循环累加
    private int currentFlowId = 0;
    private long lastCommunicateTimeStamp = 0l;
    private byte[] fileId;
    private PackageData[] data;

    public Session() {
    }

    public static String buildId(Channel channel) {
        return channel.id().asLongText();
    }

    public static Session buildSession(Channel channel) {
        return buildSession(channel, null);
    }

    public static Session buildSession(Channel channel, String phone) {
        Session session = new Session();
        session.setChannel(channel);
        session.setId(buildId(channel));
        session.setTerminalPhone(phone);
        session.setLastCommunicateTimeStamp(System.currentTimeMillis());
        return session;
    }

    public SocketAddress getRemoteAddr() {
        return this.channel.remoteAddress();
    }

    public synchronized int currentFlowId() {
        if (currentFlowId >= 0xffff)
            currentFlowId = 0;
        return currentFlowId++;
    }
}
